package com.hshit.downloader.fragment;

import java.util.Collections;
import java.util.List;

import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;

import com.hshit.downloader.R;
import com.hshit.downloader.adapter.ListMp3Adapter;
import com.hshit.downloader.adapter.ListMp3Adapter.IOnItemOptionClickListener;
import com.hshit.downloader.custom.LoadMoreListView;
import com.hshit.downloader.models.TrackInfo;
import com.hshit.downloader.services.Mp3Service;
import com.hshit.downloader.services.Mp3Service.NetworkAsyncCallback;
import com.hshit.downloader.utils.Constants;
import com.hshit.downloader.utils.Logger;

public class Mp3Fragment extends BaseFragment {
	
	LoadMoreListView mListSongs;
	
	ListMp3Adapter mAdapter;
	
	private ProgressBar mProgress;
	
	public static Mp3Fragment newInstance(int position) {
		Mp3Fragment f = new Mp3Fragment();
		Bundle b = new Bundle();
		b.putInt(Constants.TITLE_MP3, BaseFragment.TAB_MP3);
		f.setArguments(b);
		return f;
	}
	
	@Override
	public void setContentLayoutId() {
		mContentLayoutId = R.layout.fragment_mp3;
	}

	@Override
	public void onAfterView(View view) {
		setUpView(view);
		fetchSearchResult("ha%20noi");
	}
	
	private void setUpView(View view) {
		mListSongs = (LoadMoreListView) view.findViewById(R.id.list_songs);
		mProgress = (ProgressBar) view.findViewById(R.id.mProgress);
		mAdapter = new ListMp3Adapter(getActivity(), mCallback.getListTrack(), mListener);
		mListSongs.getListView().setAdapter(mAdapter);
	}
	
	private IOnItemOptionClickListener mListener = new IOnItemOptionClickListener() {
		
		@Override
		public void onOptionClick(View v, int position, int option) {
			mCallback.addNewDownloading(mCallback.getListTrack().get(position));
		}
	};
	
	public void fetchSearchResult(String keyword) {
		Mp3Service mSearch = new Mp3Service(keyword, new NetworkAsyncCallback<List<TrackInfo>>() {
			@Override
			public void onSuccess(String mKeyword, List<TrackInfo> response) {
				Logger.d(">>>>>>>>>>" + response.get(0).getTrack_link());
				mProgress.setVisibility(View.GONE);
				Collections.shuffle(response);
				mCallback.getListTrack().addAll(response);
				mAdapter.notifyDataSetChanged();
			}
			
			@Override
			public void onStart(String mKeyword) {
				mProgress.setVisibility(View.VISIBLE);
			}
			
			@Override
			public void onFailed(String mKeyword, Exception e) {
				mProgress.setVisibility(View.GONE);
			}
		});
		mSearch.work();
	}
}
